package com.butuh.uang.tuh.ang.ui;

import android.os.Bundle;
import android.os.RemoteException;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.installreferrer.api.InstallReferrerClient;
import com.android.installreferrer.api.InstallReferrerStateListener;
import com.android.installreferrer.api.ReferrerDetails;
import com.bumptech.glide.Glide;
import com.butuh.uang.tuh.ang.R;
import com.butuh.uang.tuh.ang.adapter.DetailDesAdapter;
import com.butuh.uang.tuh.ang.adapter.DetailMoneyAdapter;
import com.butuh.uang.tuh.ang.adapter.ZhaoHuiAdapter;
import com.butuh.uang.tuh.ang.model.EventDialog;
import com.butuh.uang.tuh.ang.model.HomeListBean;
import com.butuh.uang.tuh.ang.model.ProductDetailBean;
import com.butuh.uang.tuh.ang.present.PProductDetail;
import com.butuh.uang.tuh.ang.util.DecimalFormatUtil;
import com.butuh.uang.tuh.ang.util.DownLoadUtil;
import com.butuh.uang.tuh.ang.util.OnClickLogUtils;
import com.butuh.uang.tuh.ang.widget.MyGridView;
import com.butuh.uang.tuh.ang.widget.NoScrollListView;
import com.lanren.easydialog.DialogViewHolder;
import com.lanren.easydialog.EasyDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.mvp.XActivity;

public class ProductDetailActivity extends XActivity<PProductDetail> implements AdapterView.OnItemClickListener {

    @BindView(R.id.mgv_money)
    MyGridView mMgvMoney;
    @BindView(R.id.mgv_time)
    MyGridView mMgvTime;

    @BindView(R.id.iv_product_logo)
    ImageView mIvProductionLogo;

    @BindView(R.id.tv_product_name)
    TextView mTvProductionName;
    @BindView(R.id.tv_money)
    TextView mTvProductionMoney;
    @BindView(R.id.tv_lixi)
    TextView mTvProductionLiXi;
    @BindView(R.id.tv_money_all)
    TextView mTvProductionMoneyAll;

    DetailMoneyAdapter detailMoneyAdapter;

    DetailMoneyAdapter detailTimeAdapter;

    int productId;

    ProductDetailBean detailBean = null;
    @BindView(R.id.layout_data)
    RelativeLayout mLayoutData;
    @BindView(R.id.layout_no_net)
    LinearLayout mLayoutNoNet;
    @BindView(R.id.layout_error)
    LinearLayout mLayoutError;
    @BindView(R.id.tv_error_message)
    TextView mTvErrorMessage;
    @BindView(R.id.iv_kelebihan)
    ImageView mIvKelebihan;
    @BindView(R.id.tv_kelebihan)
    TextView mTvKelebihan;
    @BindView(R.id.iv_peminjaman)
    ImageView mIvPeminjaman;
    @BindView(R.id.tv_peminjaman)
    TextView mTvPeminjaman;
    @BindView(R.id.iv_syarat)
    ImageView mIvSyarat;
    @BindView(R.id.tv_syarat)
    TextView mTvSyarat;

    int indexType = 0;

    @BindView(R.id.nlv_des)
    NoScrollListView mNLvDes;

    DetailDesAdapter detailDesAdapter;

    List<ProductDetailBean.BesidesBean.TerperinciBean> mListData1;
    List<ProductDetailBean.BesidesBean.TerperinciBean> mListData2;
    List<ProductDetailBean.BesidesBean.TerperinciBean> mListData3;


    @Override
    public void initData(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);

        OnClickLogUtils.onClickLog(this, "come-in-into", "[\\\"productdetail\\\"]",0);
        productId = getIntent().getExtras().getInt("id");
        mListData1 = new ArrayList<>();
        mListData2 = new ArrayList<>();
        mListData3 = new ArrayList<>();
        detailMoneyAdapter = new DetailMoneyAdapter(this, 0);
        mMgvMoney.setAdapter(detailMoneyAdapter);
        detailTimeAdapter = new DetailMoneyAdapter(this, 1);
        mMgvTime.setAdapter(detailTimeAdapter);
        mMgvMoney.setOnItemClickListener(this);
        mMgvTime.setOnItemClickListener(this);
        detailDesAdapter = new DetailDesAdapter(this);
        mNLvDes.setAdapter(detailDesAdapter);
        mDialog.Show();
        getP().getProductDetail(productId);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(EventDialog message) {
        mDialog.Dismiss();
    }


    boolean isNew = false;
    @Override
    protected void onResume() {
        super.onResume();
        mDialog.Dismiss();
        if (isNew) {
            isNew = false;
            getP().getNewList();
        }
    }

    public void loadDataSuccess(ProductDetailBean bean) {
        mDialog.Dismiss();
        if (null != bean) {
            mLayoutData.setVisibility(View.VISIBLE);
            mLayoutNoNet.setVisibility(View.GONE);
            mLayoutError.setVisibility(View.GONE);

            detailBean = bean;
            Glide.with(context).load(bean.getIdentification()).into(mIvProductionLogo);
            mTvProductionName.setText(bean.getDesignation());
            List<Integer> moneys = new ArrayList<>();
            moneys.add(bean.getShowTheSmallestAmount());
            moneys.add(bean.getShowLargestAmountOfMoney());
            moneys.add(bean.getTunjukkanJumlahDefault());
            moneys = new ArrayList<Integer>(new LinkedHashSet<Integer>(moneys));//去重保持当前排序
            Collections.sort(moneys);//默认排序(从小到大)
            detailMoneyAdapter.setData(moneys);
            mMgvMoney.setNumColumns(moneys.size());
            int defaultIndexMoney = 0;
            for (int i = 0; i < moneys.size(); i++) {
                if (bean.getTunjukkanJumlahDefault() == moneys.get(i)) {
                    defaultIndexMoney = i;
                }
            }
            detailMoneyAdapter.setDefaultIndex(defaultIndexMoney);

            List<Integer> times = new ArrayList<>();
            times.add(bean.getShowMinimumPeriod());
            times.add(bean.getRevealMaximumPeriod());
            times.add(bean.getDisplayTheDefaultCycle());
            times = new ArrayList<Integer>(new LinkedHashSet<Integer>(times));//去重保持当前排序
            Collections.sort(times);//默认排序(从小到大)
            detailTimeAdapter.setData(times);
            mMgvTime.setNumColumns(times.size());
            int defaultIndexTime = 0;
            for (int i = 0; i < times.size(); i++) {
                if (bean.getDisplayTheDefaultCycle() == times.get(i)) {
                    defaultIndexTime = i;
                }
            }
            detailTimeAdapter.setDefaultIndex(defaultIndexTime);
            setMoneyAndLiXi();
            ProductDetailBean.BesidesBean.TerperinciBean bean1 = new ProductDetailBean.BesidesBean.TerperinciBean();
            bean1.setIkon("");
            bean1.setCaption("");
            bean1.setDetails(detailBean.getTagline());
            mListData1.add(bean1);
            for (int i = 0; i < detailBean.getBesides().size(); i++) {
                if (detailBean.getBesides().get(i).getDesignation().equals("Proses pinjaman")) {
                    mListData2.addAll(detailBean.getBesides().get(i).getTerperinci());
                } else if (detailBean.getBesides().get(i).getDesignation().equals("Syarat Pengajuan Pinjaman")) {
                    mListData3.addAll(detailBean.getBesides().get(i).getTerperinci());
                }
            }
            indexType = 1;
            switchDes();
        } else {
            mLayoutData.setVisibility(View.GONE);
            mLayoutNoNet.setVisibility(View.GONE);
            mLayoutError.setVisibility(View.VISIBLE);
            mTvErrorMessage.setText("Saat ini tidak ada produk");
        }
    }

    public void setMoneyAndLiXi() {
        int money = detailMoneyAdapter.getCurrentData();
        int time = detailTimeAdapter.getCurrentData();
        mTvProductionMoney.setText(DecimalFormatUtil.formatNumberWithMarkSplit(money, 0));
        double lixi = Double.parseDouble(detailBean.getDisplayTheLoanPeriod()) * money * time + Double.parseDouble(detailBean.getRevealCoverCharge()) * money;
        mTvProductionLiXi.setText(DecimalFormatUtil.formatNumberWithMarkSplit(lixi, 0));
        mTvProductionMoneyAll.setText(DecimalFormatUtil.formatNumberWithMarkSplit(money + lixi, 0));
    }

    public void loadDataFail(int type, String message) {
        mDialog.Dismiss();
        if (type == 1) {
            mLayoutData.setVisibility(View.GONE);
            mLayoutNoNet.setVisibility(View.VISIBLE);
            mLayoutError.setVisibility(View.GONE);
        } else {
            mLayoutData.setVisibility(View.GONE);
            mLayoutNoNet.setVisibility(View.GONE);
            mLayoutError.setVisibility(View.VISIBLE);
            mTvErrorMessage.setText(message);
        }
    }


    public void loadNewSuccess(List<HomeListBean> list) {
        showZhaoHuiDialog(list);

    }


    ZhaoHuiAdapter zhaoHuiAdapter;

    private void showZhaoHuiDialog(final List<HomeListBean> list) {
        final List<HomeListBean> mList = new ArrayList<>();
        if (list.size() < 4) {
            mList.addAll(list);
        } else {
            for (int i = 0; i < 3; i++) {
                mList.add(list.get(i));
            }
        }
        zhaoHuiAdapter = new ZhaoHuiAdapter(this);
        new EasyDialog(this, R.layout.dialog_zhaohui) {//设置自己的自定义布局文件
            @Override
            public void onBindViewHolder(DialogViewHolder holder) {
                holder.setOnClick(R.id.iv_close, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                });
                MyGridView mGv = holder.getView(R.id.gv_data);
                mGv.setNumColumns(mList.size());
                mGv.setAdapter(zhaoHuiAdapter);
                zhaoHuiAdapter.setData(mList);
                mGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        dismiss();
                        mDialog.Show();
                        HomeListBean bean = list.get(position);
                        isNew = false;
                        DownLoadUtil.download(ProductDetailActivity.this, "detail", "new", position, bean.getBianhao(), bean.getPattern(), bean.getOpenMode(), bean.getSite(), bean.getBag());
                    }
                });

            }
        }.backgroundLight(0.2)
                .setCanceledOnTouchOutside(false)
                .setCancelAble(false)
                .showDialog();
    }



    String yemianName = "detail";
    @Override
    public int getLayoutId() {
        return R.layout.activity_production_detail;
    }

    @OnClick({R.id.iv_back, R.id.tv_resume, R.id.layout_kelebihan, R.id.layout_peminjaman, R.id.layout_syarat, R.id.tv_download})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                OnClickLogUtils.onClickPermute(context, yemianName, "back", 0);
                finish();
                break;
            case R.id.tv_resume:
                OnClickLogUtils.onClickPermute(context, yemianName, "errorResume", 0);
                mDialog.Show();
                getP().getProductDetail(productId);
                break;
            case R.id.layout_kelebihan:
                if (0 != indexType) {
                    indexType = 0;
                    switchDes();
                    OnClickLogUtils.onClickPermute(context, yemianName, "kelebihan", 0);
                }
                break;
            case R.id.layout_peminjaman:
                if (1 != indexType) {
                    indexType = 1;
                    switchDes();
                    OnClickLogUtils.onClickPermute(context, yemianName, "peminjaman", 0);
                }
                break;
            case R.id.layout_syarat:
                if (2 != indexType) {
                    indexType = 2;
                    switchDes();
                    OnClickLogUtils.onClickPermute(context, yemianName, "syarat", 0);
                }
                break;
            case R.id.tv_download:
                mDialog.Show();
                isNew = true;
                DownLoadUtil.download(this, yemianName, "productdetail", 0, detailBean.getBianhao(), detailBean.getPattern(), detailBean.getOpenMode(), detailBean.getSite(), detailBean.getBag());
                break;
        }
    }

    public void switchDes() {
        switch (indexType) {
            case 0:
                mIvKelebihan.setImageResource(R.mipmap.ic_kele01);
                mTvKelebihan.setTextColor(getResources().getColor(R.color.color_title));
                mIvPeminjaman.setImageResource(R.mipmap.ic_pro00);
                mTvPeminjaman.setTextColor(getResources().getColor(R.color.color_999999));
                mIvSyarat.setImageResource(R.mipmap.ic_sya00);
                mTvSyarat.setTextColor(getResources().getColor(R.color.color_999999));
                detailDesAdapter.clearData();
                detailDesAdapter.setData(mListData1);
                break;
            case 1:
                mIvKelebihan.setImageResource(R.mipmap.ic_kele00);
                mTvKelebihan.setTextColor(getResources().getColor(R.color.color_999999));
                mIvPeminjaman.setImageResource(R.mipmap.ic_pro01);
                mTvPeminjaman.setTextColor(getResources().getColor(R.color.color_title));
                mIvSyarat.setImageResource(R.mipmap.ic_sya00);
                mTvSyarat.setTextColor(getResources().getColor(R.color.color_999999));
                detailDesAdapter.clearData();
                detailDesAdapter.setData(mListData2);
                break;
            case 2:
                mIvKelebihan.setImageResource(R.mipmap.ic_kele00);
                mTvKelebihan.setTextColor(getResources().getColor(R.color.color_999999));
                mIvPeminjaman.setImageResource(R.mipmap.ic_pro00);
                mTvPeminjaman.setTextColor(getResources().getColor(R.color.color_999999));
                mIvSyarat.setImageResource(R.mipmap.ic_sya01);
                mTvSyarat.setTextColor(getResources().getColor(R.color.color_title));
                detailDesAdapter.clearData();
                detailDesAdapter.setData(mListData3);
                break;
        }

    }

    @Override
    public PProductDetail newP() {
        return new PProductDetail();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.mgv_money:
                detailMoneyAdapter.setDefaultIndex(position);
                detailMoneyAdapter.notifyDataSetChanged();
                setMoneyAndLiXi();
                OnClickLogUtils.onClickPermute(context, yemianName, "chooseMoney", 0);
                break;
            case R.id.mgv_time:
                detailTimeAdapter.setDefaultIndex(position);
                detailTimeAdapter.notifyDataSetChanged();
                setMoneyAndLiXi();
                OnClickLogUtils.onClickPermute(context, yemianName, "chooseTime", 0);
                break;
        }
    }
}
